package chzhenjia.learn.androidcode.four;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;

import chzhenjia.learn.androidcode.R;

public class XUtilsActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etUrl;
    private ProgressBar pb;
    private TextView tvShowPb;
    public static final String TARGET_DIR = Environment.getExternalStorageDirectory().getPath();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xutils);

        Button btnDownload = (Button) findViewById(R.id.btn_download);
        btnDownload.setOnClickListener(this);

        etUrl = (EditText) findViewById(R.id.et_url);

        pb = (ProgressBar) findViewById(R.id.pb);

        tvShowPb = (TextView) findViewById(R.id.tv_show_pb);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                download();
                break;
        }
    }

    /**
     * 下载文件
     */
    private void download() {
        HttpUtils utils = new HttpUtils();
        String url = etUrl.getText().toString().trim();
        final String target = TARGET_DIR + "/" + url.substring(url.lastIndexOf("/") + 1);
        utils.download(url, target, true, true, new RequestCallBack<File>() {
            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                Toast.makeText(XUtilsActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(XUtilsActivity.this, "下载失败错误信息" + s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                pb.setMax((int) total);
                pb.setProgress((int) current);
                String showPb = (current / total * 100) + "%";
                tvShowPb.setText(showPb);
            }
        });
    }
}
